package com.sky.sd.common.web.config;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.sky.sd.common.web.convert.SkyConverterFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <br/>功能:
 * <br/>版本: 1.0
 * <br/>开发人员: 弓振
 * <br/>创建日期: 2020/6/10 13:41
 * <br/>修改日期: 2020/6/10 13:41
 * <br/>修改列表:
 */
@Configuration
public class SkyWebMvcConfig implements WebMvcConfigurer {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer(@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") String pattern){
        return builder -> {
            builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(formatter);
            LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(formatter);
            builder.serializerByType(LocalDateTime.class, serializer);
            builder.deserializerByType(LocalDateTime.class, deserializer);
        };
    }


    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new SkyConverterFactory());
    }
}
